#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：BroadviewCoss
@File    ：send_dingtalk_msg.py
@IDE     ：PyCharm
@Author  ：kdly
@Date    ：2025/4/8 下午1:27
'''
import base64
import hashlib
import hmac
import json
import time

import logging
import requests
from urllib.parse import quote_plus

logger = logging.getLogger()
# 修改权限
logger.setLevel(logging.INFO)


def gen_sign(timestamp, secret):
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = quote_plus(base64.b64encode(hmac_code))
    return sign


def send_dingtalk_message(webhook_url, sign, alert_data):
    """
    向飞书群机器人发送消息
    :param webhook_url: 钉钉群机器人的Webhook地址
    :param sign: 钉钉群机器人的签名
    :param alert_data: 要发送的消息内容 alert_data = {
        "group": "测试组",
        "type": "进程监控",
        "name": "test",
        "obj": "nginx",
        "hostname": "127.0.0.1",
        "status": 0,
        "error": "Probe failed",
        "start_time": "2025-04-02 16:27:28",
        "end_time": "2025-04-02 16:30:13"
    }
    :return: API响应内容
    """
    # 构建消息内容
    if alert_data['status'] == 0:

        content = """**<font color="red">BroadviewCoss告警信息</font>**\n\n"""
    else:
        content = """**<font color="green">BroadviewCoss告警恢复</font>**\n\n """

    content += f"""监控分组: {alert_data['group']}\n
监控类型: {alert_data['type']}\n
监控名称: {alert_data['name']}\n
监控对象: {alert_data['obj']}\n"""

    if alert_data['status'] == 0:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}\n
详细信息: {alert_data['error']}\n
故障时间: {alert_data['start_time']}\n"""
        else:
            content += f"""
详细信息: {alert_data['error']}\n
故障时间: {alert_data['start_time']}\n"""

    else:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}\n
详细信息: {alert_data['error']}\n
故障时间: {alert_data['start_time']}\n
恢复时间: {alert_data['end_time']}\n"""

        else:
            content += f"""
详细信息: {alert_data['error']}\n
故障时间: {alert_data['start_time']}\n
恢复时间: {alert_data['end_time']}\n"""

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }

    message = {
        "msgtype": "markdown",
        "markdown": {
            "title": "BroadviewCoss告警信息",
            "text": content,
        },
        "at": {
            "atMobiles": [
                ""
            ],
            "atUserIds": [
                ""
            ],
            "isAtAll": False
        }
    }
    if not webhook_url:
        return
    try:
        timestamp = str(round(time.time() * 1000))  # 返回浮点数形式的秒级时间戳（含小数部分）,转换为10位整数秒级时间戳
        sign = gen_sign(timestamp, sign)

        # 计算签名密钥并修改url
        webhook_url += f"&timestamp={timestamp}&sign={sign}"
        # 发送请求并打印
        requests.post(webhook_url, headers=header, data=json.dumps(message))
    except requests.exceptions.RequestException as e:
        logger.error(f"发送钉钉群告警失败：{str(e)}")
        return False
    return True


if __name__ == "__main__":
    alert_data = {
        "group": "测试组",
        "type": "测试类型",
        "name": "测试",
        "obj": "nginx",
        "error": "error",
        "status": 0,
        "hostname": '测试主机',
        "start_time": "2025年04月 14:25",
        "end_time": "2025年04月 14:25",
    }
    send_dingtalk_message(
        'https://oapi.dingtalk.com/robot/send?access_token=xxx',
        'xxx', alert_data)
